/*
#author				Chieh-Hsin Fan
#e-mail				chiehhsin.fan@gmail.com
#version			0.1
*/

Array.prototype.findIndex = function(value){
	var ctr = -1;
	for (var i=0; i < this.length; i++) {
	// use === to check for Matches. ie., identical (===), ;
		if (this[i] == value) {
			return i;
		}
	}
	return ctr;
};
var DispMode = {"Individual":0, "Summary":1, "Random":2};
var SearchMode = {"AND":0, "OR":1, "Closed":2};
var relatedPost = {
		//start of user define
		numRelatedPosts: 5,
		numPostFromRecent: 20,
		colorLabel: "",
		displayMode: DispMode.Summary,
		searchmode: SearchMode.Closed,
		//end of user define
		relatedPostsNum: 0,
		relatedTitles: new Array(),
		relatedUrls: new Array(),
		relatedDates: new Array(),
		relatedLabel: new Array(),
		getPostInfo: function (idx) {
			var labels = "";
			if(this.relatedLabel[idx]){
				for (var i = 0; (i < this.relatedLabel[idx].length); i++)
					labels += this.relatedLabel[idx][i]+",";
			}
			return '<li><a href="' + this.relatedUrls[idx] + '">' + this.relatedTitles[idx] + '</a> - ' + this.relatedDates[idx] + " "+labels+'</li>';
		},
		ShowRelatedPosts: function (Labels, removeURL) {
			//mode 0:and 1:or
			//output posts which contains Label
			//alert("Related Post num:"+this.relatedPostsNum);
			var output = "";
			var outputA = new Array(Labels.length);
			var idxLabel=0;
			if(Labels.length == 1)
				relatedPost.searchmode = SearchMode.OR;
			else if(Labels.length == 0)
				output = "";

			if(relatedPost.searchmode == SearchMode.AND){
				var targets = new Array();
				//filter match posts
				for (var i = 0; (i < this.numPostFromRecent); i++) {
					if((this.relatedLabel[i])&&(this.relatedLabel[i].length>=Labels.length)&&(this.relatedUrls[i] != removeURL)){
		 				for (idxLabel = 0; (idxLabel < Labels.length); idxLabel++) {
							if((this.relatedLabel[i].findIndex(Labels[idxLabel])<0)){
								break;
							}
		 				}
		 				if(idxLabel >= Labels.length){
		 					targets.push(i);
		 				}
		 			}
				}
				var used = new Array(targets.length);
				//random select posts
				for (var i = 0, idx = 0; (idx < this.numRelatedPosts)&&(i < targets.length); i++) {
	 				r=Math.floor(Math.random()*targets.length);
	 				if(used[r]!=-1){
						output += this.getPostInfo(targets[r]);
						idx++;
					}
					used[r] = -1;
				}
			}else if(relatedPost.searchmode == SearchMode.OR){
				var used = new Array(this.numPostFromRecent);
				for (var i = 0, idx=0; (idx < this.numRelatedPosts)&&(i < this.numPostFromRecent); i++) {
	 				r=Math.floor(Math.random()*this.numPostFromRecent);
	 				if((used[r]!=-1)&&(this.relatedLabel[r])&&(this.relatedLabel[r].length>0)&&(this.relatedUrls[r] != removeURL)){
		 				for (idxLabel = 0; (idxLabel < Labels.length); idxLabel++) {
							if(this.relatedLabel[r].findIndex(Labels[idxLabel])>=0){
								break;
							}
		 				}
						if(idxLabel < Labels.length){
							output += this.getPostInfo(r);
							idx++;
						}
					}
					used[r] = -1;
				}
			}else if(relatedPost.searchmode == SearchMode.Closed){
				var targets = new Array(Labels.length+1);
				var matchN = 0;

				for (var i = 0; (i < targets.length); i++) {
					targets[i] = new Array();
				}
				//order posts with matched num of labels
				for (var idxPosts = 0; (idxPosts < this.numPostFromRecent); idxPosts++) {
					matchN = 0;
					if((this.relatedLabel[idxPosts])&&(this.relatedLabel[idxPosts].length > 0)){
						for (var idxLabel = 0; (idxLabel < Labels.length); idxLabel++) {
							if(this.relatedLabel[idxPosts].findIndex(Labels[idxLabel])>=0){
								matchN++;
							}
						}
					}
					if(this.relatedUrls[idxPosts] != removeURL)
					targets[matchN].push(idxPosts);
				}
				//select posts from targets[] from most matched
				var outPostLeft = this.numRelatedPosts;
				for (var i = targets.length-1; i>=0; i--) {
					if(targets[i].length > outPostLeft){
						var used = new Array(targets[i].length);
						//random select posts
						for (var j = 0; (j < outPostLeft); ) {
			 				r=Math.floor(Math.random()*targets[i].length);
			 				if(used[r]!=-1){
								output += this.getPostInfo(targets[i][r]);
								used[r] = -1;
								j++;
							}
						}
						break;
					}else{ //put all targets in outPosts[]
						for (var j = 0; (j < targets[i].length); j++) {
							output += this.getPostInfo(targets[i][j]);
						}
						outPostLeft -= targets[i].length;
					}
				}


			}

			return output;

		},
		ShowRandomPosts: function (Labels, removeURL) {
			var output = "";
			var used = new Array(this.numPostFromRecent);
			for (var i = 0, idx=0; (idx < this.numRelatedPosts)&&(i < this.numPostFromRecent); i++) {
 				r=Math.floor(Math.random()*this.numPostFromRecent);
 				if((used[r]!=-1)&&(this.relatedUrls[r] != removeURL)){
					output += this.getPostInfo(r);
					idx++;
				}
				used[r] = -1;
			}
			return output;
		},
		insetRelatedPosts: function(){
			//var numLabel = $("div[class='post-footer'] a[href*=search/label]").length;
			var numPosts = $("div[class='post-footer']").length;
			//alert(numLabel+":"+numPosts);
			if(relatedPost.displayMode == DispMode.Individual){
				var Labels;
				var url;
				for (var i = 0; (i < numPosts); i++) {
					Labels = new Array();
					url = $("[class='post-title entry-title']:eq("+i+") a[href]").attr( "href" );
					$("div[class='post-footer']:eq("+i+") a[href*=search/label]").each( function(){
					if(relatedPost.colorLabel=="")
						relatedPost.colorLabel = $(this).css("color").val();
					$(this)
					.css("color",relatedPost.colorLabel)
					//.css("font-size","medium")
					.css("font-weight","bold")
					.before("<br>")
						.after(relatedPost.ShowRelatedPosts(new Array($(this).text()),url));
				});
				}
			}else if(relatedPost.displayMode == DispMode.Summary){
				var Labels;
				var url;
				for (var i = 0; (i < numPosts); i++) {
					Labels = new Array();
					url = $("[class='post-title entry-title']:eq("+i+") a[href]").attr( "href" );
					$("div[class='post-footer']:eq("+i+") a[href*=search/label]")
					.css("color",relatedPost.colorLabel)
					.css("font-weight","bold")
					.each(function(){
						//document.write(i+":"+$(this).text()+"<BR>");
						Labels.push($(this).text());
					});
					$("div[class='post-footer']:eq("+i+") a[href*=search/label]:last")
					.after("<br>")
					.after(relatedPost.ShowRelatedPosts(Labels,url));
				}
			}else if(relatedPost.displayMode == DispMode.Random){
				var Labels;
				var url;
				for (var i = 0; (i < numPosts); i++) {
					Labels = new Array();
					url = $("[class='post-title entry-title']:eq("+i+") a[href]").attr( "href" );
					$("div[class='post-footer']:eq("+i+") a[href*=search/label]")
					.css("color",relatedPost.colorLabel)
					.css("font-weight","bold")
					.each(function(){
						//document.write(i+":"+$(this).text()+"<BR>");
						Labels.push($(this).text());
					});
					$("div[class='post-footer']:eq("+i+") a[href*=search/label]:last")
					.after("<br>Random Post suggestion<BR>")
					.after(relatedPost.ShowRandomPosts(Labels,url));
				}
			}

		}
};
function RelatedLabels (json) {

	var regex1 = new RegExp("<", "gi");
	var regex2 = new RegExp(">", "gi");
	if(relatedPost.numPostFromRecent > json.feed.entry.length)
		relatedPost.numPostFromRecent = json.feed.entry.length;
	for (var i = 0; (relatedPost.relatedPostsNum < relatedPost.numPostFromRecent)&&(i < json.feed.entry.length); i++) {

	  var entry = json.feed.entry[i];
	  relatedPost.relatedTitles[relatedPost.relatedPostsNum] = (entry.title.$t);
	  relatedPost.relatedDates[relatedPost.relatedPostsNum] = entry.published.$t.substr(0,10);
	  if(entry.category){
		  relatedPost.relatedLabel[relatedPost.relatedPostsNum] = new Array(entry.category.length);
		  for (var j = 0; j < entry.category.length; j++) {
		  		relatedPost.relatedLabel[relatedPost.relatedPostsNum][j] = entry.category[j].term;
			}
		}else{
			relatedPost.relatedLabel[relatedPost.relatedPostsNum] = null;
		}
	  for (var j = 0; j < entry.link.length; j++) {
	    if (entry.link[j].rel == 'alternate') {
	      relatedPost.relatedUrls[relatedPost.relatedPostsNum] = entry.link[j].href;
	      relatedPost.relatedPostsNum++;
	      break;
	    }
	  }
//	  if((relatedPost.relatedUrls[relatedPost.relatedPostsNum-1]==document.URL)&&(relatedPost.relatedPostsNum>0))
//	  	relatedPost.relatedPostsNum--;


	}
}